#pragma once 

#include <iostream>
#include <cstdlib>
#include <string>
#include <pthread.h>
using namespace std;

typedef void (*func_t)(void*);

class Thread
{
public:
    typedef enum
    {
        NEW=0,
        RUNNING,
        EXITED
    } ThreadStatus;
public:
    Thread(int num,func_t func,void* args)
        :_tid(0)
        ,_status(NEW)
        ,_args(args)
        ,_func(func)
    {
        char name[128] ;
        snprintf(name,sizeof(name),"thread-%d",num);
        _name = name;
    }

    int status()
    {
        return _status;
    }

    string threadname()
    {
        return _name;
    }

    pthread_t threadid()
    {
        if(_status != RUNNING)
            return _tid;
        else
        {
            cout << "no tid" << endl;
            return 0;
        }
            
    }

    //类的成员函数具有默认的参数this，参数不匹配
    //但没有了this指针，也无法直接访问类内成员函数和变量
    static void* runHelper(void* args)
    {
        //Thread* th = static_cast<Thread*> args;
        Thread* th = (Thread*) args;
        (*th)();
        return nullptr;
    }

    //仿函数
    void operator()()
    {
        _func(_args);
    }

    void run()
    { 
        int n = pthread_create(&_tid,nullptr,runHelper,this);
        if(n != 0) exit(1);
        _status = RUNNING;

    }

    void join()
    {
        int n = pthread_join(_tid,nullptr);
        if(n != 0)
        {
            cerr << "main thread join thread" << _name << endl;
        }
    }

    ~Thread()
    {

    }
private:
    pthread_t _tid;
    string _name;
    func_t _func;//将来要回调的函数
    void* _args;  //喂给func的参数
    ThreadStatus _status;
};